package pers.qianyu.month_202101.date_20210125;

/**
 * 剑指 Offer 19. 正则表达式匹配
 * https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/
 *
 * @author mizzle rain
 * @date 2021-01-25 14:27
 */
public class IsMatch {
    public boolean isMatch(String s, String p) {
        int n = s.length(), m = p.length();
        boolean[][] dp = new boolean[n + 1][m + 1];
        dp[0][0] = true;
        for (int j = 2; j <= m; j += 2) dp[0][j] = dp[0][j - 2] && p.charAt(j - 1) == '*';
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (p.charAt(j - 1) == '*') {
                    dp[i][j] = dp[i][j - 2] || dp[i][j - 1] ||
                            (p.charAt(j - 2) == s.charAt(i - 1)) && dp[i - 1][j] ||
                            p.charAt(j - 2) == '.' && dp[i - 1][j];
                } else {
                    dp[i][j] = dp[i - 1][j - 1] &&
                            (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.');
                }
            }
        }
        return dp[n][m];
    }
}
